<?php
namespace Common\Model;
use Think\Model;
class EntDepartmentModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_ent_department'; 
	
	
	public function getAllDepart(){
		$result = $this->field('departid,departname,pid,entid')->select();
		return $result;
	}
	
	public function getDepartByPid($pid , $entid=0){
		$map['qyx_ent_department.pid'] = $pid;
		if(!empty($entid)) $map['qyx_ent_department.entid'] = $entid;
		$result = $this->join('left join qyx_ent_department p on qyx_ent_department.pid=p.departid')
						->field('qyx_ent_department.departid,qyx_ent_department.departname,qyx_ent_department.custnum,qyx_ent_department.pid,p.departname as pdepartname,qyx_ent_department.entid')
						->where($map)->select();
		if(empty($result)) $result = array();
		return $result;
	}
	
	public function getChildCnt($pids){
		$map = array();
		if(is_array($pids)) $map['pid'] = array('in' , $pids);
		$result = $this->field('pid,count(departid) as cnt')->where($map)->group('pid')->select();
		return $result;
	}
	
	public function getDepartById($departid , $entid=0){
		$map['qyx_ent_department.departid'] = $departid;
		if(!empty($entid)) $map['qyx_ent.entid'] = $entid;
		$result = $this->join('join qyx_ent on qyx_ent_department.entid=qyx_ent.entid')
						->field('qyx_ent_department.departid,qyx_ent_department.departname,qyx_ent_department.custnum,qyx_ent_department.pid,qyx_ent_department.entid,qyx_ent_department.mcustid,qyx_ent_department.chatid,qyx_ent.custid')
						->where($map)->find();
		if(empty($result)) $result = array();
		return $result;
	}
	
	public function getDepartByIds($departids){
		$map['departid'] = array('in' , $departids);
		$result = $this->field('departid,departname,pid,entid,mcustid,chatid,custnum')->where($map)->select();
		return $result;
	}
	
	public function getDepartByEnt($entid){
		$map['entid'] = $entid;
		$result = $this->field('departid,departname,pid,entid,mcustid,chatid,custnum')->where($map)->select();
		return $result;
	}
	
	public function addDepart($data){
		$result = $this->add($data);
		return $result;
	}
	
	
	public function updateDepart($data){
		$map['departid'] = $data['departid'];
		$map['entid'] = $data['entid'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
	
	public function deleteDepart($data){
		$map['departid'] = $data['departid'];
		$map['entid'] = $data['entid'];
		$result = $this->where($map)->delete();
		return $result;
	}
	
	
	public function custNumInr($departid , $num){
		$sql = "update qyx_ent_department set custnum=custnum+{$num} where departid = {$departid}";
		$this->execute($sql);
	}
	
	public function custNumDecr($departid , $num){
		$sql = "update qyx_ent_department set custnum=custnum-{$num} where departid = {$departid}";
		$this->execute($sql);
	}
}


